<!--导出excel-->
<template>
    <el-drawer
            :title="'导出:'+fileName+'/'+sheetName"
            :visible.sync="drawerVisible"
            size="400px"
            append-to-body
            :show-close="!exporting"
            :before-close="evtClose"
            :close-on-press-escape="false"
            :destroy-on-close="true"
            :with-header="true">
        <div style="padding: 10px; height:100%; overflow-y: auto; ">
            <el-card shadow="hover" style="margin-bottom:10px">
                <div style="color:#666;font-weight: bold;margin-bottom:10px">导出哪些列？
                    <el-checkbox  :indeterminate="isIndeterminate" v-model="radio" @change="handleCheckAllChange" style="">
                        全选
                    </el-checkbox>
                </div>
                <div style="color:#666; margin-bottom:20px; ">
                    <el-checkbox-group v-model="checkeds" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for=" item in columns"
                                     :label="item.prop"
                                     style="font-size: 12px; font-weight: normal; margin:6px 10px;"
                                     :key="item.prop">
                            {{item.label}}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
            </el-card>
            <el-card shadow="hover" style="">
                <div style="color:#666;font-weight: bold;margin-bottom:10px">导出文件名称</div>
                <div style="color:#666; margin-bottom:20px; ">
                    <el-input v-model="sheetName" placeholder="请输入导出文件名称">
                        <template slot="append">.xlsx</template>
                    </el-input>
                </div>
            </el-card>
            <div style="width:100%; margin-top:20px;  margin-bottom:40px;  text-align: center">
                <div v-show="exporting"  v-text="exportingMsg"></div>
                <el-progress :text-inside="true" v-show="exporting" :stroke-width="26"
                             :percentage="exportPercentage"></el-progress>
                <el-button type="primary" style="width:160px;margin-top:20px;" @click="exportSubmit"
                           v-show="!exporting"
                           :disabled="this.rows===0 ">导出数据
                </el-button>
            </div>
        </div>
    </el-drawer>
</template>
<script>
    import XLSX from 'xlsx'
    export default {
        name: "exporExcel",
        data() {
            return {
                drawerVisible: false,
                checkeds: [],
                exporData: [],
                inputFileName: this.sheetName,
                inputSheetName: this.sheetName,
                exportPercentage: 0,
                exporting: false,
                exportingMsg: "正在获取数据",
                fields: "code,name",
                radio:true,
                isIndeterminate:true
            }
        },
        props: {
            fileName: {
                type: String,
                default: '默认导出数据'
            },
            sheetName: {
                type: String,
                default: '默认导出数据'
            },
            rows: {
                type: Number,
                default: 0
            },
            columns: null,
            query: null,
            exportApi: null,
            tableId: {
                type: String,
                default: "",
            }, //某些独特参数
            extend:null,
            isPerSon:{
                 type:Boolean,
                 default:false
            }
        },
        methods: {
            handleCheckAllChange(val){
                let that = this;
                if(val){
                    that.checkeds = [];
                    this.columns.forEach(function (item) {
                        that.checkeds.push(item.prop);
                    })
                }else {
                    that.checkeds = []
                }
                this.isIndeterminate = false;
            },
            handleCheckedCitiesChange(value) {
                let checkedCount = value.length;
                this.radio = checkedCount === this.columns.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.columns.length;
            },
            //来自父组件调用
            exportOpen() {
                let that = this
                that.checkeds = [];
                this.columns.forEach(function (item) {
                    that.checkeds.push(item.prop);
                })
                this.drawerVisible = true
            },
            evtClose(done) {
                done(!this.exporting)
            },
            async exportSubmit() {
                let that = this
                //获取字段
                if(that.checkeds.length===0){
                    that.$message.error("请选择要需要导入字段项目")
                    return
                }
                that.exportPercentage=0;
                that.fields=that.checkeds.join(",")
                that.exporting = true
                let pageSize = 50
                let page = {}
                that.exporData = []
                let headerTitle = {}
                that.checkeds.forEach(function (item) {
                    headerTitle[item]=that.columns.filter(col=>col.prop===item)[0].label
                });
                that.exporData.push(headerTitle)
                if(this.rows!==""){
                    let pages = Math.ceil(that.rows / pageSize)
                    that.exportingMsg = "正在获取数据"
                    for (let i = 1; i <= pages; i++) {
                        page = {"pageSize": pageSize, "pageIndex": i}
                        let res = await that.funLoadData(page)
                        that.exportPercentage = parseInt((i / pages) * 100);
                        that.exporData = that.exporData.concat(res.rows || res.data.rows || res.data );
                    }
                }else {
                    let page;
                    let res = await that.funLoadData(page)
                    that.exporData = that.exporData.concat(res.rows || res.data.rows || res.data );
                }
                that.exportingMsg = "正在写文件"
                setTimeout(function () {
                        let newArr=[],objItem={};
                            that.exporData.map((cols) => {
                                objItem={};
                                that.fields.split(",").map(v=>{
                                    objItem[v] = cols[v]
                                });
                                newArr.push(objItem)
                            });
                            that.exporData = newArr;
                    const header = {header: that.checkeds, skipHeader:true}
                    const ws = XLSX.utils.json_to_sheet(that.exporData, header)
                    const wb = XLSX.utils.book_new()
                    XLSX.utils.book_append_sheet(wb, ws, that.sheetName)
                    XLSX.writeFile(wb, that.sheetName + ".xlsx")
                    that.exporting = false
                    that.drawerVisible = false
                }, 100);
            },
            funLoadData(page) {
                let that = this;
                return new Promise((resolve, reject) => {
                    if(that.query.tag==='buildGate'){
                        that.exportApi(that.query.areaId,that.query.buildingId,page.pageIndex,page.pageSize,that.fields).then((res) => {
                            resolve(res)
                        }).catch((err) => {
                            reject(err)
                        })
                    }else if(that.query.tag==='lateNightRecord'){
                        that.exportApi(JSON.stringify(that.query.search),JSON.stringify(page),that.query.order,that.fields).then((res) => {
                            resolve(res)
                        }).catch((err) => {
                            reject(err)
                        })
                    }else{
                        that.exportApi(
                            JSON.stringify(that.query.search),
                            JSON.stringify(page),
                            that.query.tableOrder,
                            that.fields,
                            that.extend,
                            that.tableId,
                    ).then((res) => {
                            if(that.tableId){
                                resolve(res.data)
                            }else{
                                resolve(res)
                            }
                        }).catch((err) => {
                            reject(err)
                        })
                    }
                })
            }
        },
        created() {}
    }
</script>
<style scoped lang="scss">
    //::v-deep{
    //     .el-checkbox__input.is-checked+.el-checkbox__label {
    //         color: #5054F0 !important;
    //     }
    //     .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    //         background-color: #5054F0 !important;
    //         border-color: #5054F0 !important;
    //     }
    //     .el-button--primary {
    //         color: #FFF;
    //         background-color: #5054F0 !important;
    //         border-color: #5054F0 !important;
    //     }
    // } 
</style>

